# Preliminaries ####

rm(list = ls())
library(tidyverse)
library(texreg)
library(ROCR)
library(survival)
library(kableExtra)
library(ggthemes)

# data ####
d <- read.csv("data_main_aan25_militias_neg.csv")
names(d)

# Table 1: Descriptive Statistics ####

# select variables of interest
# na.omit model selection:
dx <- d |>
   dplyr::select(
      Year,
      Negotiation, Mediation,
      Mil_vs_Reb_dm, Mil_vs_Civ, Mil_vs_Gov,
      Mil_vs_Reb_all,
      impgdppcln, imppopln, v2x_polyarchy, dydurln,
      Intensity_rate_lag,  lull, brd_d_ln,
      Ethnicincomp, rebno_ct,
      violence_civ_gov_lag_ln, violence_civ_reb_lag_ln,
      PrevMed_5y, UN, Internationalized,
      RebTerCont, RebPolWingLeg,  RebExpSup
   ) |>
   na.omit()

desc_tab <- data.frame(
   N = apply(dx, 2, length),
   Mean = apply(dx, 2, mean),
   SD = apply(dx, 2, sd), 
   Min = apply(dx, 2, min), 
   p25 = apply(dx, 2, quantile, probs = 0.25), 
   Median = apply(dx, 2, quantile, probs = 0.50), 
   p75 = apply(dx, 2, quantile, probs = 0.75), 
   Max = apply(dx, 2, max)
   )

# round 
desc_tab <- apply(desc_tab, 2, round, 2)
desc_tab[1, ] <- round(desc_tab[1, ], 0)

# variable names:
data.frame(rownames(desc_tab))
rownames(desc_tab) <- 
   c(
   "Year", 
   "Negotiation",
   "Mediation",
   "Militia vs Rebel",
   "Militia vs Civilian", 
   "Militia vs Government",
   "Militia vs Other Rebels",
   "GDP Per capita (ln)", 
   "Population (ln)",
   "V-Dem Polyarchy",
   "Duration (ln)",
   "Intensity rate",
   "Lull in Fighting", 
   "Battle-related Deaths",
   "Ethnic Conflict",
   "No. of Rebel Groups",
   "Government vs Civilians", 
   "Rebel vs Civilians", 
   "Previous Mediation", 
   "UN PKO",
   "Internationalized Conflict",
   "Rebel Territorial Control",
   "Rebel Political Wing Legal",
   "Rebel External Support")

# save the html file: 
save_kable(knitr::kable(desc_tab, format = "html"), file = "table_01.html")

# Figure 1: Key statistics visualized ####

## info:
dx <- d |>
   dplyr::select(
      Negotiation, Mediation,
      Mil_vs_Reb_dm, Mil_vs_Civ, Mil_vs_Gov,
      Mil_vs_Reb_all,Mil_vs_Reb_all,
      Intensity_rate_lag,  lull, brd_d_ln,
      impgdppcln, imppopln, v2x_polyarchy, dydurln, Ethnicincomp, rebno_ct,
      PrevMed_5y, UN, Internationalized, odapcln,
      RebTerCont, RebPolWingLeg, exit_lag, v2x_clphy,
      tsln, tsln2, tsln3, DyadId, Year, GWNoA, SideA) |>
   na.omit()


# calculations
dx1 <- dx |> 
   select(SideA, Year, 
          Mil_vs_Civ, 
          Mil_vs_Gov, 
          Mil_vs_Reb_all) |>
   unique() |>
   group_by(SideA) |>
   mutate(Civilians = sum(Mil_vs_Civ),
          Government = sum(Mil_vs_Gov),
          Rebels = sum(Mil_vs_Reb_all),
   ) |>
   ungroup() |>
   select(SideA, Civilians, Government, Rebels) |>
   unique() |>
   mutate(All = Civilians + Government + Rebels)


# turn from wide to long
dfig <- dx1 |> 
   pivot_longer(
      cols = c("Rebels", "Civilians", "Government"),
      names_to = "type", 
      values_to = "activity")

dfig$g <- findInterval(
   x = dfig$All, 
   vec = c(min(dfig$All), 100, 500)
   )

dfig$g <- factor(
   dfig$g,
   levels = c(3,2,1),
   labels = c("High", "Medium", "Low")
   )

dfig$type <- factor(
   dfig$type, 
   levels = rev(c("Civilians", "Government", "Rebels")),
   labels = rev(c("Civilians", "Government", "Rebels"))
   )

dfig$SideA[dfig$SideA == "Central African Republic"] <- "CAR"
dfig$SideA[dfig$SideA == "DR Congo (Zaire)"] <- "DR Congo"

#colors
cols <- c('#e66101','#fdb863','#b2abd2','#5e3c99')
cols <- c('#b2abd2', '#5e3c99', '#e66101')


# Barplot direct (without panels)
dfig |> 
   ggplot(aes(y = reorder(SideA, activity), x = activity, fill = type)) + 
   geom_bar(stat = "identity") +
   labs(x = "Number of Militia Attacks", y = NULL,
        fill = "Target")  + 
   scale_x_continuous(expand = c(0, 0)) +
   theme_minimal() +
   theme(legend.position =  c(0.80, 0.11),
         legend.background = element_rect(fill = "grey95", color = "black"),
         axis.text = element_text(colour = "black", size=11, face = "bold"), 
         legend.text = element_text(size = 11, colour = "black", face = "bold"),
         strip.text.y = element_text(face = "bold", size = 12, colour = "black", angle = 270)) +
   theme(plot.margin=grid::unit(c(0,0,0,0), "mm")) +
   scale_fill_manual(values = cols)

## Figure 1: Panel B ####
# Barplot with panels: 
plt_mil <- dfig |> 
   ggplot(aes(y = reorder(SideA, activity), x = activity, fill = type)) + 
   geom_bar(stat = "identity") +
   ggh4x::facet_grid2(g ~ ., scales = "free", independent = "x", space = "free_y") +
   labs(x = "Total Number of Militia Attacks", y = NULL,
        fill = "Target")  + 
   scale_x_continuous(expand = c(0, 0)) +
   theme_minimal() +
   theme(legend.position =  c(0.80, 0.11),
         legend.background = element_rect(fill = "grey95", color = "black"),
         legend.title = element_text(size = 12, colour = "black", face = "bold"),
         axis.text = element_text(colour = "black", size=11, face = "bold"), 
         legend.text = element_text(size = 11, colour = "black", face = "bold"),
         axis.title  = element_text(colour = "black", size=12, face = "bold"),
         strip.text.y = element_text(face = "bold", size = 12, colour = "black", angle = 270)) +
   theme(plot.margin=grid::unit(c(0,0,0,0), "mm")) +
   scale_fill_manual(values = cols)

plt_mil

## Figure 2: Panel C:  Negotiations ####
dy <- dx |>
   select(DyadId, Year, Negotiation, Mediation) |> 
   unique() |> 
   group_by(Year) |>
   mutate(n = n(),
          sum_neg = sum(Negotiation),
          sum_med = sum(Mediation)) |>
   ungroup() |>
   select(Year, n, sum_neg, sum_med) |>
   unique()

dy$no_talks <- dy$n - dy$sum_neg
dy$bilateral <- dy$sum_neg - dy$sum_med


dfig2 <- dy |> 
   pivot_longer(
      cols = c("no_talks", "sum_med", "bilateral"),
      names_to = "type", 
      values_to = "activity")

dfig2$type <- factor(dfig2$type, 
                     levels = rev(c("no_talks", "sum_med", "bilateral")),
                     labels = rev(c("No Talks", "Mediated Talks", "Bilateral Talks")))


plt_neg <- dfig2 |> 
   ggplot(aes(y = activity, x = Year, fill = type)) +
   geom_col() +
   labs(x = "Year", y = "Number of Dyads",
        fill = "Negotiation Status") +
   scale_x_continuous(
      labels = unique(dfig2$Year),
      breaks = unique(dfig2$Year),
      expand = c(0.01, 0.01)
   ) +
   theme_minimal() +
   theme(legend.position =  c(0.775, 0.85),
         legend.background = element_rect(fill = "grey95", color = "black"),
         legend.text = element_text(size = 11, colour = "black", face = "bold"),
         legend.title = element_text(size = 11, colour = "black", face = "bold"),
         axis.text.x = element_text(colour = "black", size=11, 
                                    face = "bold", 
                                    angle = 45),
         axis.text.y = element_text(colour = "black", size=11, face = "bold"),
         axis.title  = element_text(colour = "black", size=12, face = "bold")
   ) +
   theme(plot.margin=grid::unit(c(0,0,0,0), "mm")) +
   scale_fill_manual(values = cols)

plt_neg

